from django.shortcuts import render,HttpResponse
from user.models import User
# Create your views here.


def index(request):
    # 查找到所有的user对象
    users=User.objects.all()
    # 渲染模板，传递user
    return render(request,'index.html',context={'users':users})


def add(request):
    if request.method == 'GET':
        # 如果是get，打开页面
        return render(request,'add.html')
    else:
        # 获取页面提交的数据
        username=request.POST.get('username')
        password=request.POST.get('password')
        age=request.POST.get('age')
        email=request.POST.get('email')
        try:
            # 提交用户数据
            User(username=username,password=password,age=age,email=email).save()
            return render(request,'result.html',{'message':'新增用户成功'})
        except:
            return render(request, 'result.html', {'message': '新增用户失败'})


def alter(request,id):
    # 获取用户信息
    user=User.objects.get(id=id)
    if request.method == 'GET':
        # 如果是get，打开页面
        return render(request,'alter.html',context={'user':user})
    else:
        # 获取页面提交的数据
        user.username=request.POST.get('username')
        user.password=request.POST.get('password')
        user.age=request.POST.get('age')
        user.email=request.POST.get('email')
        try:
            # 提交保存用户信息
            user.save()
            return render(request,'result.html',context={'message':'修改用户成功'})
        except:
            return render(request,'result.html',context={'message':'修改用户失败'})


def delete(request,id):
    try:
        # 删除用户
        User.objects.get(id=id).delete()
        return render(request,'result.html',context={'message':'删除用户成功'})
    except:
        return render(request,'result.html',context={'message':'删除用户失败'})

